﻿
using System.Collections.Generic;
using FibMatrix.DS;

namespace FibMatrix
{
    /// <summary>
    /// Resources目录资源模式的实现
    /// </summary>
    [FM_Mono.IgnoreGen]
    public class DefaultResourceFacadeImpl : AbstractResourceFacadeImpl
    {
        private ObjectPool2<ResourcePipelineContext> _contextPool = new ObjectPool2<ResourcePipelineContext>(-1, () => new ResourcePipelineContext());

        public override string GenerateLoadURL(string prefix, string localPath, string extension)
        {
            return prefix + localPath;
        }

        protected override ResourcePipelineContext CreatePipelineContext()
        {
            return _contextPool.Allocate();
        }

        protected override void DestroyPipelineContext(ResourcePipelineContext context)
        {
            _contextPool.Recycle(context);
        }

        protected override List<IResourceLoadPipe> CreateSyncLoadPipes(IResourceInitConfig initConfig)
        {
            return new List<IResourceLoadPipe>
                {
                    new DefaultLoadAssetPipe()
                };
        }

        protected override List<IResourceLoadPipe> CreateAsyncLoadPipes(IResourceInitConfig initConfig)
        {
            return new List<IResourceLoadPipe>
                {
                    new DefaultAsyncLoadAssetPipe()
                };
        }

        protected override bool ReleaseLoadItem(AbstractLoadItem item)
        {
            RemoveInstanceIdFromLoadItem(item);

            item.objRefCount = 0;
            item.instanceID = -1;
            bool needUnloadUnusedAsset = false;
            if (item.assetHandle != null)
            {
                needUnloadUnusedAsset = (item.assetHandle as DefaultUAssetLoadHandle).Unload();
                item.assetHandle = null;
            }
            return needUnloadUnusedAsset;
        }


        protected override void UnloadAll()
        {
            var iter = this._loadItemMap.GetEnumerator();
            while (iter.MoveNext())
            {
                var item = iter.Current.Value;
                if (item.assetHandle != null)
                {
                    (item.assetHandle as DefaultUAssetLoadHandle).Unload();
                    item.assetHandle = null;
                }
            }
            this._loadItemMap.Clear();
        }
    }
}
